package com.world.rickcloudendpoint.queue;

import org.omg.CORBA.Object;

/**
 * @description: 环形队列：方式2 (非线程安全的，需要线程安全，给读写指针增加volatile关键字)
 * @author: jlsong
 * @date: 2022/05/30 09:14:29
 * @version: 1.0
 */
public class CircularBuffer<T> {

    private final int DEFAULT_CAPACITY = 1024 * 10;

    // 数组容量
    private int capacity;
    // 读位置
    public volatile int readPos = 0;
    // 写位置
    public volatile int writePos = -1;
    // 数据容器
    private T[] items;

    public CircularBuffer(int capacity) {
        this.capacity = capacity < 1 ? DEFAULT_CAPACITY : capacity;
        this.items = (T[]) new Object[this.capacity];
        this.readPos = 0;
        this.writePos = -1;
    }

    // 向环形队列放元素
    public boolean offer(T item) {
        boolean isFull = (writePos - readPos + 1 == capacity);
        if (!isFull) {
            int nextWritePos = writePos + 1;
            items[nextWritePos % capacity] = item;
            writePos++;
            return true;
        }
        return false;
    }

    // 从环形队列取元素
    public T poll() {
        boolean isEmpty = writePos < readPos;
        if (!isEmpty) {
            T nextValue = items[readPos & capacity];
            readPos++;
            return nextValue;
        }
        return null;
    }
}
